package com.huluobo.hyj.hyjmodel.contract.login

import com.huluobo.hyj.hyjmodel.adapter.EMCallbackAdapter
import com.huluobo.hyj.hyjmodel.extention.isValidUserName
import com.huluobo.hyj.hyjmodel.extention.isValidUserPassword
import com.hyphenate.chat.EMClient

/**
 * 登录中mvp中P层和m层的实现
 * */
class LoginPresenter(val view :LoginContract.View) :LoginContract.Presenter {
    //登录
    override fun login(UserName: String, password: String) {
        //用户名是否合法
        if(UserName.isValidUserName()){
            //密码是否合法
            if(password.isValidUserPassword()){
                //登录qa
                view.onstartLogin()//触发回调，让view层开始响应
                //登录到环信
                loginEaseMob(UserName,password)
            }else view.onUserpasswordError()
        }else view.onUserNameError()
    }

    //登录的M层
    private fun loginEaseMob(userName: String, password: String) {
      //实现具体mvp中的m层
        EMClient.getInstance().login(userName,password,object :EMCallbackAdapter(){
            override fun onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups()
                EMClient.getInstance().chatManager().loadAllConversations()
                runOnUiThread {  view.onLoggedInSuccess()}

            }

            override fun onError(code: Int, error: String?) {
                runOnUiThread { view.onLoggedInFailed() } //更新Ui所以要在子线程主线程中运行
//                view.onLoggedInFailed()

            }
        })
    }
}